from django.contrib.auth.backends import ModelBackend

from users.models import User


class MyModelBackend(ModelBackend):

    # 重写authenticate
    def authenticate(self, request, username=None, password=None, **kwargs):

        if not request is None:
            try:
                user = User.objects.get(mobile=username)
            except Exception as e:
                try:
                    user = User.objects.get(username=username)
                except Exception as e:
                    return None

            if user.check_password(raw_password=password):
                return user

        else:
            try:
                user = User.objects.get(username=username, is_staff=True, is_superuser=True)
            except:
                try:
                    user = User.objects.get(mobile=username, is_staff=True, is_superuser=True)
                except:
                    return None

            if user.check_password(raw_password=password):
                return user